package util;

import java.awt.Component;

import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CenterPanel extends JPanel{
	
	private double rate;//拉伸比例
	private JComponent c;//显示的组件
	private boolean strech;//是否拉伸
	
	public CenterPanel(double rate,boolean strech) {
		this.setLayout(null); //null为绝对布局,其他参数为north,south,west....
		this.rate = rate;
		this.strech = strech;
	}
	
	public CenterPanel(double rate) {
		this(rate,true);
	}
	
	
	public void repaint() {
		if(null != c) {
			/*
			 *dimension类是一种容器，封装了一个构件的高度和宽度
			   * 与Dimension类相关方法：getSize()和setSize(Dimension size)。分别用来获得和设置方格的大小。
			 */
			//containerSize获取面板的size
			Dimension containerSize = this.getSize();
			//componentSize获取JComponent组件的size
			Dimension componentSize = c.getPreferredSize();
			
			if(strech)
				c.setSize((int)(containerSize.width * rate), (int)(containerSize.height * rate));
			else
				c.setSize(componentSize);
			
			c.setLocation(containerSize.width/2-c.getSize().width/2,containerSize.height/2-c.getSize().height/2);	
		}
		super.repaint();
	}
	
	/*
	 * show的思想是先将所有组件都移出，再把新的组件添加进容器，然后再更新ui
	 * show函数会调用updateUI()函数，upadteUI则会调用repaint()方法
	 */
	public void show(JComponent p) {
		this.c = p;
		Component[] cs = getComponents();
		for(Component c:cs) {
			remove(c);
		}
		add(p);
		this.updateUI();
	}
	
	public static void main(String[] args) {
		JFrame f =new JFrame();
		f.setSize(200,200);
		//setLocationRelativeTo(Component c)设置窗口相对于指定组件的位置。null为屏幕中央
		f.setLocationRelativeTo(null);
		CenterPanel cp=new CenterPanel(0.5,true);
		//setContentPane()方法获得JFrame的内容面板
		f.setContentPane(cp);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
		JButton b =new JButton("abc");
		cp.show(b);
	}

}
